import React, { useState } from 'react';
import { StyleSheet } from 'react-native';

// Add setImmediate polyfill
if (typeof setImmediate === 'undefined') {
  // @ts-ignore
  window.setImmediate = function (callback: Function, ...args: any[]) {
    return setTimeout(callback, 0, ...args);
  };
}

import { MonoText } from '../StyledText';
import { Text, View, Image } from '../Themed';
import Swiper from 'react-native-swiper';

import Colors from '@/constants/Colors';
import { swiperParamList } from '@/constants/globalDataApi';

// 使用require方式加载本地图片
// 提取轮播项为独立组件
const SlideItem = ({ slide, index }: { slide: swiperParamList; index: number }) => (
  <View style={styles.slide1}>
    <Text style={styles.title1}>{slide.title}</Text>
    <Text style={styles.description}>{slide.description}</Text>
    <Image style={styles.image} source={slide.image} resizeMode="cover" />
  </View>
);
export default function SwiperModule() {
  const [slides, setSlides] = useState<swiperParamList[]>([
    { id: 1, title: '精选课程', description: '探索最新的教育资源', image: require('../../assets/images/icon1.png') },
    { id: 2, title: '学习指导', description: '获取专业的学习建议', image: require('../../assets/images/icon2.png') },
    { id: 3, title: '考试资料', description: '准备充分迎接挑战', image: require('../../assets/images/icon3.png') },
  ]);

  // 简化状态管理，只保留当前索引
  const [currentIndex, setCurrentIndex] = useState(0);
  const onIndexChanged = (index: number) => {
    setCurrentIndex(index);
  };
  return (
    <Swiper
      style={styles.swiperWrap}
      loop={true}
      autoplay={true}
      autoplayTimeout={5}
      onIndexChanged={(index) => onIndexChanged(index)}
      paginationStyle={{ bottom: 10 }}
      showsButtons={true}
      removeClippedSubviews={false}
      loadMinimal={true}
      loadMinimalSize={2}
    >
      {slides.map((slide, index) => (
        <SlideItem key={slide.id} slide={slide} index={index} />
      ))}
    </Swiper>
  );
}

const styles = StyleSheet.create({
  swiperWrap: {
    width: '100%',
    height: 280, // 增加高度以适应导航按钮
  },
  slide1: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderRadius: 10,
  },

  title1: {
    color: '#000',
    fontSize: 22,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  description: {
    color: '#333',
    fontSize: 16,
    marginBottom: 15,
    textAlign: 'center',
    paddingHorizontal: 20,
  },
  image: {
    // width: '100%',
    // height: 200,
    borderRadius: 8,
  },
});
